<template>
  <el-table
    v-bind="$attrs"
    style="width: 100%"
    v-loading="loading"
    :stripe="true"
    :border="false"
    :data="tableData"
  >
    <slot />
  </el-table>
  <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="currentPageSize"
      :background="true"
      :layout="paginationLayout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</template>

<script setup lang="ts">
import { tableQuery } from '@/api/sys/sys'
import { defineProps, ref, onMounted, nextTick, defineExpose } from 'vue'
import tableProps from './tableProps'
const props = defineProps(tableProps)

const loading = ref(true)
const currentPage = ref(1)
const currentPageSize = ref(10)
const tableData = ref<object[]>([])
const total = ref(0)
// 组件初始化
onMounted(() => {
  if (props.type === 'remote') {
    currentPage.value = 1
    currentPageSize.value = 10
  }
  if (props.autoLoad) {
    query()
  }
})
// 查询
const query = () => {
  loading.value = true
  if (props.type === 'local') {
    tableData.value = props.localData
    loading.value = false
    return
  }
  if (!props.url) {
    console.error('请配置table的url')
  }
  const params = Object.assign(
    { current: currentPage.value, size: currentPageSize.value },
    props.where
  )
  // console.log(params)
  tableQuery(props.url, params).then(res => {
    tableData.value = res.data.records
    total.value = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}
// 每页条数变更
const handleSizeChange = (val: number) => {
  currentPage.value = val
  query()
}
// 当前页数变更
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  query()
}
// 手动触发重载表格数据
// resetPage 是否回到第一页
const reload = (resetPage = false) => {
  nextTick(() => {
    if (resetPage) {
      currentPage.value = 1
    }
    query()
  })
}
defineExpose({
  reload
})
</script>

<style scoped>
.pagination {
  margin: 12px 0 0 0;
}
</style>
